import { reqGetCode, reqLogin, reqLogout, reqRegisterInfo ,reqUserInfo,reqAddressList} from '@/api'
import {getUserTempId} from '@/utils/userAbout'
const state = {
    // 获取用户的唯一标识
    userTempId:getUserTempId(),
    code:'',
    // token:'',
    token:localStorage.getItem('TOKEN_KEY'),
    userInfo:{},
    userAddressList:[]
}
const mutations = {
    RECEIVE_CODE(state,code){
        state.code = code
    },
    RECEIVE_TOKEN(state,token){
        state.token = token
    },
    RECEIVE_USERINFO(state,userInfo){
        state.userInfo = userInfo
    },
    RESET_TOKEN(state){
        state.token = '',
        state.userInfo = {}
    },
    REVEICE_USERADDRESSLIST(state,userAddressList){
        state.userAddressList = userAddressList
    }
}
const actions = {
    // 获取验证码
    async getCode({commit},phone){
        const result = await reqGetCode(phone)
        if (result.code === 200) {
            commit('RECEIVE_CODE',result.data)
            return result.data
        }else{
            return Promise.reject(new Error('failed'))
        }
    },
    // 请求注册
    async getRegister({commit},userInfo){
        const result = await reqRegisterInfo(userInfo)
        if (result.code === 200) {
            return 'ok'
        }else{
            return Promise.reject(new Error('failed'))
        }
    },
    // 请求登录
    async getLogin({commit},userInfo){
        const result = await reqLogin(userInfo)
        if (result.code === 200) {
            commit('RECEIVE_TOKEN',result.data.token)
            // 将token存储到localStorage中实现自动登录
            localStorage.setItem('TOKEN_KEY',result.data.token)
            return result.data.token
        }else{
            return Promise.reject(new Error('failed'))
        }
    },
    // 请求用户信息
    async getUserInfo({commit}){
        const result = await reqUserInfo()
        if (result.code === 200) {
            commit('RECEIVE_USERINFO',result.data)
            return 'ok'
        }else{
            return Promise.reject(new Error('failed'))
        }
    },
    // 清空token
    async resetToken({commit}){
        commit('RESET_TOKEN')//将存在state中的token删掉
        localStorage.removeItem('TOKEN_KEY')//将存在localStroage中的token删除
    },
    // 退出登录
    async logout({commit,dispatch}){
        const result = await reqLogout()
        if (result.code === 200) {
            dispatch('resetToken')//退出登录成功,清除state当中的token和用户信息,还有 localStorage当中的token信息
            return 'ok'
        }else{
            return Promise.reject(new Error('failed'))
        }
    },
    // 请求用户地址信息
    async getUserAddressList({commit}){
        const result = await reqAddressList()
        if (result.code === 200) {
            commit('REVEICE_USERADDRESSLIST',result.data)
        }
    }
}
const getters = {}

export default {
    state,
    mutations,
    actions,
    getters
}